package com.pp.controller;

import com.pp.common.BaseResponse;
import com.pp.common.ErrorCode;
import com.pp.common.ResultUtils;
import com.pp.model.Furn;
import com.pp.service.FurnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping ("/furn")
@RestController
public class FurnController {
    @Autowired
    private FurnService furnService;

    ///新增接口
    @PostMapping("/save")
    public BaseResponse<Object>  addFurn(@Validated @RequestBody Furn furn,Errors errors){
        HashMap<String, Object> map = new HashMap<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError:fieldErrors){
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        if (map.isEmpty()){
            //先写存储 在写提交参数错误处理
            boolean save=furnService.insert(furn)>0;
            return ResultUtils.success(save);
        }
         return  ResultUtils.error(ErrorCode.PARAMS_ERROR,map);

    }

    //分页接口
    @GetMapping("getByPage")
    public BaseResponse<Map<String,Object>> getList(@RequestParam(defaultValue = "5") int pageSize,
                                                    @RequestParam(defaultValue = "1") int pageNum,
                                                    @RequestParam(defaultValue = "",required = false) String search){

        int offset=(pageNum-1)*pageSize;
        List<Furn> data=furnService.selectByPage(offset,pageSize,search);
        int total=furnService.count(search);
        HashMap<String, Object> map= new HashMap<>();
        map.put("data",data);
        map.put("total",total);
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        return ResultUtils.success(map);
    }
    @GetMapping("/getById")
    public BaseResponse<Furn> getById(@RequestParam("id") Integer id){
        return ResultUtils.success(furnService.selectById(id));
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> update(@RequestBody Furn furn){
        return ResultUtils.success(furnService.update(furn)>0);
    }

    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> delete(@PathVariable("id") Integer id){
        return ResultUtils.success(furnService.deleteById(id)>0);
    }

}
